// stores/contacts.js
import {
	defineStore
} from 'pinia';
import {
	getFriendListApi,
	getGroupListApi,
	getGroupUserApi,
	getGroupNoticeApi,
	getApplyApi,
	postApplyApi,
	putRemarksApi,
	delFriendApi,
	postGroupApi,
} from '@/api/contacts';
import {
	useSocketStore,
} from '@/stores/socket';

export const useContactsStore = defineStore('contacts', {
	state: () => {
		return {
			userId: '', // 在首页登录成功加载时 获取值
			friendList: [], // 好友列表
			groupList: [], // 群组列表
			groupUserMap: {}, // 群组对应的用户  哈希数据结构
			groupNoticeMap: {}, // 群组对应的群公告  哈希数据结构
			friendApplyList: [], // 好友申请列表
			groupApplyList: [], // 群组申请列表
			topList: {
				'friend': {
					name: '新朋友',
					headImg: '/static/img/contacts/new_friend.png',
					id: 'friend',
					badge: 0,
				},
				'groupchat': {
					name: '群聊',
					headImg: '/static/img/contacts/group_chat.png',
					id: 'groupchat',
				},
				'group': {
					name: '群通知',
					headImg: '/static/img/contacts/group_notice.png',
					id: 'group',
					badge: 0,
				}
			}
		};
	},
	getters: {
		friendMap: (state) => state.friendList.reduce((pre, v) => {
			pre[v.friendId] = v;
			return pre;
		}, {}),
		friendNameMap: (state) => state.friendList.reduce((pre, v) => {
			pre[v.friendId] = v.nameRemark || v.friendName;
			return pre;
		}, {}),
		groupMap: (state) => state.groupList.reduce((pre, v) => {
			pre[v.id] = v;
			return pre;
		}, {}),
		groupUserAllMap: (state) => {
			let obj = {};
			for (let key in state.groupUserMap) {
				obj[key] = state.groupUserMap[key].reduce((pre, v) => {
					pre[v.uid] = v;
					return pre;
				}, {})
			}
			return obj;
		},
		frinedIdList: (state) => state.friendList.map(item => item.friendId),
		groupIdList: (state) => state.groupList.map(item => item.id),
	},
	actions: {
		// 获取用户所有好友
		async getFriendList() {
			try {
				let {
					data
				} = await getFriendListApi({
					page: 1,
					limit: 500,
					mainAccountID: this.userId,
				});

				if (data.data.code == 1) {
					this.friendList = data.data.data.records.map(item => {
						item.address = item.address ? JSON.parse(item.address) : [];
						return item;
					});
				} else {
					throw Error(data);
				}
			} catch (e) {
				throw Error(e)
			}
		},
		// 获取用户单个好友
		async getFriend(friendId) {
			try {
				let {
					data
				} = await getFriendListApi({
					page: 1,
					limit: 1,
					mainAccountID: this.userId,
					friendId,
				});
				if (data.data.code == 1) {
					let obj = data.data.data.records[0];
					obj.address = obj.address ? JSON.parse(obj.address) : [];
					this.friendList.push(obj);
				} else {
					throw Error(data);
				}
			} catch (e) {
				// throw Error(e)
			}
		},
		// 获取用户所有群组
		async getGroupList(params = {}) {
			try {
				let {
					data
				} = await getGroupListApi({
					page: 1,
					limit: 200,
					uid: this.userId,
					...params
				});

				if (data.data.code == 1) {
					this.groupList = data.data.data.records;
					this.groupList.forEach(item => {
						this.getGroupUser(item.id);
						this.getGroupNotice(item.id);
					});
				} else {
					throw Error(data.data.message);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 获取用户单个群组
		async getGroup(params = {}) {
			try {
				let {
					data
				} = await getGroupListApi({
					page: 1,
					limit: 1,
					uid: this.userId,
					...params
				});


				let index = this.groupList.findIndex(item => item.id == params.gid);
				if (data.data.code == 1) {
					if (data.data.data.records.length !== 0) {
						index === -1 && this.groupList.push(...data.data.data.records);
						this.getGroupUser(params.gid);
						this.getGroupNotice(params.gid);
					} else {
						if (index !== -1) {
							this.groupList.splice(index, 1);
							delete this.groupUserMap[params.gid];
							delete this.groupNoticeMap[params.gid];
						}
					}
				} else {
					throw Error(data);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 新增群组
		async addGroup({
			groupName,
			groupUsers,
		}) {
			try {
				let {
					data
				} = await postGroupApi({
					groupName,
					createUser: this.userId,
					groupUsers,
				});

				console.log(data);
				if (data.data.code == 1) {
					this.groupList.push(data.data.data.info);
					await this.getGroupUser(data.data.data.info.id);
					await this.getGroupNotice(data.data.data.info.id);
					return data.data.data.info;
				} else {
					throw Error(data);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 获取当前群组所有的用户
		async getGroupUser(gid) {
			try {
				let {
					data
				} = await getGroupUserApi({
					page: 1,
					limit: 500,
					gid,
				});
				if (data.data.code == 1) {
					this.groupUserMap[gid] = data.data.data.records;
				} else {
					throw Error(data);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 获取当前群组的群公告
		async getGroupNotice(gid) {
			try {
				let {
					data
				} = await getGroupNoticeApi({
					page: 1,
					limit: 500,
					gid,
				});
				if (data.data.code == 1) {
					this.groupNoticeMap[gid] = data.data.data;
				} else {
					throw Error(data);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 获取当前用户所有好友或群组的申请
		async getApplyList(params = {}) {
			try {
				let {
					data
				} = await getApplyApi({
					page: 1,
					limit: 500,
					receiveId: this.userId,
					state: '[0, 1]',
					...params
				});

				if (data.data.code == 1) {
					// 1：添加好友；
					if (!params.type || params.type == 1) {
						this.friendApplyList = data.data.data.records.filter(item => item.type == 1);
					}
					// 2：加入群组；
					if (!params.type || params.type == 2) {
						this.groupApplyList = data.data.data.records.filter(item => item.type == 2);
					}
				} else {
					throw Error(data);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 获取当前用户新增的好友或群组的申请
		async getApply(params = {}) {
			try {
				let {
					data
				} = await getApplyApi({
					page: 1,
					limit: 1,
					receiveId: this.userId,
					state: '[0, 1]',
					...params
				});

				if (data.data.code == 1) {
					switch (Number(params.type)) {
						case 1:
							this.friendApplyList.unshift(...data.data.data.records);
							break;
						case 2:
							this.groupApplyList.unshift(...data.data.data.records);
							break;
						default:
							break;
					}

					return data.data.data.records[0];
				} else {
					throw Error(data);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 新增好友或群组的申请
		async addApply(params = {}, groupUsers) {
			try {
				let {
					data
				} = await postApplyApi({
					sendId: this.userId,
					state: 0,
					...params
				}, {
					title: ' 发送请求中'
				});

				if (data.data.code == 1) {
					const socket = useSocketStore();
					switch (Number(params.type)) {
						case 1:
							socket.send({
								type: 3,
								receive: params.receiveId,
								info: {
									id: data.data.data.id
								},
							});
							break;
						case 2:
							socket.send({
								type: 4,
								groupId: params.groupId,
								groupUsers: JSON.stringify(groupUsers),
								info: {
									id: data.data.data.id
								},
							});
							break;
						default:
							break;
					}

					uni.navigateBack();
				} else {
					uni.showToast({
						title: data.data.message,
						position: 'top',
					});
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 修改好友或群组的申请 为 同意
		async putApply(params = {}) {
			try {
				let {
					data
				} = await postApplyApi({
					state: 1,
					id: params.id
				}, {
					title: '同意申请中'
				});

				let index = -1;
				let obj = null;
				switch (Number(params.type)) {
					case 1:
						index = this.friendApplyList.findIndex(item => item.id == params.id);
						this.friendApplyList[index].state = 1;
						obj = this.friendApplyList[index];
						break;
					case 2:
						index = this.groupApplyList.findIndex(item => item.id == params.id);
						this.groupApplyList[index].state = 1;
						obj = this.groupApplyList[index];
						break;
					default:
						break;
				}

				if (data.data.code == 1) {
					const socket = useSocketStore();
					switch (Number(params.type)) {
						case 1:
							socket.send({
								type: 7,
								receive: obj.sendId,
							});
							this.getFriend(obj.sendId);
							break;
						case 2:
							socket.send({
								type: 5,
								receive: obj.sendId,
								groupId: obj.groupId,
							});
							socket.send({
								type: 17,
								groupId: obj.groupId,
								groupUsers: JSON.stringify(this.groupUserMap[obj.groupId].map(
									item => item.uid).filter(id => id != this.userId)),
							});
							this.getGroupUser(obj.groupId);
							break;
						default:
							break;
					}
				} else {
					uni.showToast({
						title: data.data.message,
						position: 'top',
					});
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 修改好友的备注名
		async putRemarks({
			id,
			nameRemark,
		}) {
			try {
				if (this.friendMap[id]?.nameRemark == nameRemark) return Promise.reject(false);
				let {
					data
				} = await putRemarksApi({
					id,
					nameRemark,
				});

				if (data.data.code == 1) {
					let index = this.friendList.findIndex(item => item.id == id);
					this.friendList[index]['nameRemark'] = nameRemark;
					return Promise.resolve(true);
				} else {
					return Promise.reject(false);
				}
			} catch (e) {
				throw Error(e);
			}
		},
		// 删除好友
		async delFriend(id, friendId) {
			let {
				data
			} = await delFriendApi({
				uid: this.userId,
				ids: JSON.stringify([id]),
			});
			if (data.data.code == 1) {
				let index = this.friendList.findIndex(item => item.id == id);
				this.friendList.splice(index, 1);
				const socket = useSocketStore();
				socket.send({
					type: 22,
					receive: friendId,
				});
			}
		},
		/* 通讯录的badge */
		// 新增
		addBadge(name, id) {
			this.getApply({
				type: name == 'friend' ? 1 : 2,
				id
			});
			this.topList[name].badge = 1 + Number(this.topList[name].badge);
			uni.setTabBarBadge({
				index: 1,
				text: this.topList['friend'].badge + this.topList['group'].badge
			});
		},
		// 删除
		delBadge(name) {
			this.topList[name].badge = 0;
		}

	},
	unistorage: true,
});
